import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import NProgress from '@/utils/nprogress.js'
import Login from '@/views/login/index.vue'
import route from './route'
import { useUserStore } from '@/stores'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      meta: {
        title: '登录',
      },
      component: Login,
    },
    ...route,
    //  重定向
    {
      path: '/:pathMatch(.*)*',
      redirect: 'login',
    },
  ],
})
router.beforeEach((to, from, next) => {
  const { userInfo } = useUserStore()
  // 开启进度条
  NProgress.start()
  if (to.name === 'login') {
    next()
  } else {
    if (userInfo.user_token) {
      next()
    } else {
      next({ name: 'login' })
    }
  }
})
router.afterEach((to, from) => {
  // 关闭进度条
  NProgress.done()
})
export default router
